<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-info">
        <div class="greeting">
          <span class="time">{{ greeting }}</span>
          <span class="username">{{ userInfo.username }}</span>
        </div>
        <div class="date">{{ currentDate }}</div>
      </div>
      <div class="weather-info">
        <el-icon><Sunny /></el-icon>
        <span>25°C 晴朗</span>
        <span class="location">深圳市</span>
      </div>
    </div>

    <!-- 核心数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6" v-for="(item, index) in statistics" :key="index">
        <el-card class="data-card" :class="item.type" shadow="hover">
          <div class="card-body">
            <div class="icon-wrapper">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="data-info">
              <div class="title">{{ item.title }}</div>
              <div class="value">{{ item.value }}</div>
              <div class="trend">
                <span :class="{ 'up': item.growth > 0, 'down': item.growth < 0 }">
                  {{ item.growth > 0 ? '+' : '' }}{{ item.growth }}%
                </span>
                较上周
                <el-icon :class="{ 'up': item.growth > 0, 'down': item.growth < 0 }">
                  <component :is="item.growth > 0 ? 'ArrowUpBold' : 'ArrowDownBold'" />
                </el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <div class="left">
                  <h3>销售趋势</h3>
                  <el-tag effect="plain" type="info">近7天交易数据</el-tag>
                </div>
                <div class="right">
                  <el-radio-group v-model="timeRange" size="small">
                    <el-radio-button label="week">本周</el-radio-button>
                    <el-radio-button label="month">本月</el-radio-button>
                    <el-radio-button label="year">全年</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>
            <div class="chart-content">
              <div id="salesChart" style="width: 100%; height: 100%;"></div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <div class="left">
                  <h3>商品分类</h3>
                  <el-tag effect="plain" type="info">销售占比</el-tag>
                </div>
              </div>
            </template>
            <div class="chart-content">
              <div id="categoryChart" style="width: 100%; height: 100%;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作区 -->
    <div class="quick-actions">
      <el-card shadow="hover">
        <template #header>
          <div class="section-header">
            <h3>快捷操作</h3>
          </div>
        </template>
        <div class="action-grid">
          <div v-for="(action, index) in quickActions" 
               :key="index"
               class="action-item"
               @click="handleQuickAction(action)">
            <el-icon><component :is="action.icon" /></el-icon>
            <span>{{ action.name }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 实时动态 -->
    <el-row :gutter="20" class="realtime-section">
      <el-col :span="12">
        <el-card shadow="hover" class="latest-orders">
          <template #header>
            <div class="section-header">
              <div class="left">
                <h3>最新订单</h3>
                <el-tag effect="plain" type="info">实时更新</el-tag>
              </div>
              <el-button link type="primary">查看更多</el-button>
            </div>
          </template>
          <el-table :data="latestOrders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="180" />
            <el-table-column prop="product" label="商品" />
            <el-table-column prop="amount" label="金额" width="100">
              <template #default="{ row }">
                <span class="amount">¥{{ row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status.type" size="small">
                  {{ row.status.text }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card shadow="hover" class="system-info">
          <template #header>
            <div class="section-header">
              <div class="left">
                <h3>系统信息</h3>
                <el-tag effect="plain" type="info">运行状态</el-tag>
              </div>
              <el-button link type="primary">刷新</el-button>
            </div>
          </template>
          <div class="info-list">
            <div class="info-item" v-for="(info, index) in systemInfo" :key="index">
              <span class="label">{{ info.label }}</span>
              <div class="value">
                <el-progress 
                  :percentage="info.value" 
                  :color="info.color"
                  :stroke-width="8"
                  :show-text="false"
                />
                <span class="text">{{ info.value }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { 
  Money, ShoppingCart, User, Goods, ArrowUpBold, ArrowDownBold,
  Plus, Upload, Setting, Download, Sunny
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

// 定义时间范围类型
type TimeRange = 'week' | 'month' | 'year'
const timeRange = ref<TimeRange>('week')

// 获取问候语
const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '凌晨好'
  if (hour < 9) return '早上好'
  if (hour < 12) return '上午好'
  if (hour < 14) return '中午好'
  if (hour < 17) return '下午好'
  if (hour < 19) return '傍晚好'
  return '晚上好'
})

// 当前日期
const currentDate = computed(() => {
  return dayjs().format('YYYY年MM月DD日 dddd')
})

// 核心统计数据
const statistics = [
  {
    title: '总销售额',
    value: '¥126,560',
    growth: 12.3,
    icon: 'Money',
    type: 'primary'
  },
  {
    title: '订单数量',
    value: '1,234',
    growth: 8.5,
    icon: 'ShoppingCart',
    type: 'success'
  },
  {
    title: '新增用户',
    value: '156',
    growth: -2.8,
    icon: 'User',
    type: 'warning'
  },
  {
    title: '商品总数',
    value: '1,789',
    growth: 5.2,
    icon: 'Goods',
    type: 'info'
  }
]

// 快捷操作
const quickActions = [
  { name: '新增订单', icon: 'Plus', path: '/order/create' },
  { name: '商品上架', icon: 'Upload', path: '/product/create' },
  { name: '系统设置', icon: 'Setting', path: '/system/settings' },
  { name: '数据导出', icon: 'Download', path: '/data/export' }
]

// 最新订单
const latestOrders = [
  {
    orderNo: 'DD20240101001',
    product: '高级商务笔记本',
    amount: '6,799',
    status: { type: 'success', text: '已完成' }
  },
  {
    orderNo: 'DD20240101002',
    product: '无线蓝牙耳机',
    amount: '999',
    status: { type: 'warning', text: '待发货' }
  },
  {
    orderNo: 'DD20240101003',
    product: '智能手表',
    amount: '2,399',
    status: { type: 'primary', text: '已发货' }
  }
]

// 系统信息
const systemInfo = [
  { label: 'CPU使用率', value: 65, color: '#409EFF' },
  { label: '内存使用率', value: 45, color: '#67C23A' },
  { label: '磁盘使用率', value: 78, color: '#E6A23C' },
  { label: '带宽使用率', value: 32, color: '#909399' }
]

// 销售趋势数据类型定义
interface SalesData {
  dates: string[]
  sales: number[]
  orders: number[]
}

interface SalesDataMap {
  week: SalesData
  month: SalesData
  year: SalesData
}

// 销售趋势数据
const salesData: SalesDataMap = {
  week: {
    dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    sales: [120, 132, 101, 134, 90, 230, 210],
    orders: [220, 182, 191, 234, 290, 330, 310]
  },
  month: {
    dates: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
    sales: [820, 932, 901, 934, 1290, 1330, 1320],
    orders: [720, 832, 801, 834, 1190, 1230, 1220]
  },
  year: {
    dates: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
    sales: [2820, 2932, 2901, 2934, 3290, 3330, 3320],
    orders: [2720, 2832, 2801, 2834, 3190, 3230, 3220]
  }
}

// 商品分类数据类型定义
interface CategoryItem {
  value: number
  name: string
}

const categoryData: CategoryItem[] = [
  { value: 1048, name: '电子产品' },
  { value: 735, name: '服装服饰' },
  { value: 580, name: '食品饮料' },
  { value: 484, name: '家居用品' },
  { value: 300, name: '其他' }
]

// 初始化销售趋势图表
const initSalesChart = () => {
  const chartDom = document.getElementById('salesChart')
  if (!chartDom) return
  
  const myChart = echarts.init(chartDom)
  const currentData = salesData[timeRange.value]
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['销售额', '订单量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: currentData.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      {
        type: 'value',
        name: '订单量',
        axisLabel: {
          formatter: '{value} 单'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: currentData.sales,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.3)' },
            { offset: 1, color: 'rgba(64,158,255,0.1)' }
          ])
        }
      },
      {
        name: '订单量',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: currentData.orders,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103,194,58,0.3)' },
            { offset: 1, color: 'rgba(103,194,58,0.1)' }
          ])
        }
      }
    ]
  }

  myChart.setOption(option)
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 初始化商品分类图表
const initCategoryChart = () => {
  const chartDom = document.getElementById('categoryChart')
  if (!chartDom) return
  
  const myChart = echarts.init(chartDom)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: categoryData
      }
    ]
  }

  myChart.setOption(option)
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 监听时间范围变化
watch(timeRange, () => {
  initSalesChart()
})

onMounted(() => {
  initSalesChart()
  initCategoryChart()
})

// 处理快捷操作点击
const handleQuickAction = (action: any) => {
  if (action.path) {
    router.push(action.path)
  }
}

// 添加路由
const router = useRouter()
</script>

<style lang="scss" scoped>
.dashboard {
  .welcome-section {
    background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-5) 100%);
    padding: 24px;
    border-radius: 12px;
    color: #fff;
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .welcome-info {
      .greeting {
        font-size: 24px;
        font-weight: 600;
        margin-bottom: 8px;
        
        .username {
          margin-left: 8px;
          opacity: 0.9;
        }
      }
      
      .date {
        font-size: 14px;
        opacity: 0.8;
      }
    }
    
    .weather-info {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      
      .location {
        font-size: 14px;
        opacity: 0.8;
        margin-left: 8px;
      }
    }
  }

  .data-overview {
    margin-bottom: 24px;
    
    .data-card {
      .card-body {
        display: flex;
        align-items: center;
        gap: 16px;
        
        .icon-wrapper {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          
          .el-icon {
            font-size: 24px;
          }
        }
        
        .data-info {
          flex: 1;
          
          .title {
            font-size: 14px;
            color: var(--el-text-color-regular);
            margin-bottom: 8px;
          }
          
          .value {
            font-size: 24px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin-bottom: 8px;
          }
          
          .trend {
            font-size: 13px;
            color: var(--el-text-color-secondary);
            display: flex;
            align-items: center;
            gap: 4px;
            
            .up {
              color: #67C23A;
            }
            
            .down {
              color: #F56C6C;
            }
          }
        }
      }
      
      &.primary .icon-wrapper {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
      
      &.success .icon-wrapper {
        background-color: var(--el-color-success-light-9);
        color: var(--el-color-success);
      }
      
      &.warning .icon-wrapper {
        background-color: var(--el-color-warning-light-9);
        color: var(--el-color-warning);
      }
      
      &.info .icon-wrapper {
        background-color: var(--el-color-info-light-9);
        color: var(--el-color-info);
      }
    }
  }

  .chart-section {
    margin-bottom: 24px;
    
    .chart-card {
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .left {
          display: flex;
          align-items: center;
          gap: 12px;
          
          h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
          }
        }
      }
      
      .chart-content {
        height: 350px;
      }
    }
  }

  .quick-actions {
    margin-bottom: 24px;
    
    .action-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 16px;
      
      .action-item {
        height: 80px;
        background-color: var(--el-fill-color-lighter);
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        .el-icon {
          font-size: 24px;
          color: var(--el-color-primary);
        }
        
        span {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
        
        &:hover {
          transform: translateY(-2px);
          background-color: var(--el-color-primary-light-9);
        }
      }
    }
  }

  .realtime-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .left {
        display: flex;
        align-items: center;
        gap: 12px;
        
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
        }
      }
    }
    
    .latest-orders {
      .amount {
        font-family: monospace;
        color: var(--el-color-primary);
      }
    }
    
    .system-info {
      .info-list {
        .info-item {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          
          .label {
            width: 100px;
            color: var(--el-text-color-regular);
          }
          
          .value {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 12px;
            
            .text {
              min-width: 45px;
              color: var(--el-text-color-secondary);
            }
          }
        }
      }
    }
  }
}
</style> 